<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.1.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/hexo/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/hexo/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/hexo/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/hexo/images/logo.svg" color="#222">

<link rel="stylesheet" href="/hexo/css/main.css">


<link rel="stylesheet" href="/hexo/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"youchen12138.gitee.io","root":"/hexo/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="前言安装 1npm install --save egg-sequelize mysql2  配置 12345678910111213141516&#x2F;&#x2F; config&#x2F;plugin.tssequelize: &amp;#123;  enable: true,  package: &amp;#x27;egg-sequelize&amp;#x27;,&amp;#125;,    &#x2F;&#x2F; config&#x2F;config.defaullt.ts">
<meta property="og:type" content="article">
<meta property="og:title" content="egg+ts使用sequelize">
<meta property="og:url" content="https://youchen12138.gitee.io/hexo/2020/08/25/egg-ts%E4%BD%BF%E7%94%A8sequelize/index.html">
<meta property="og:site_name" content="幽辰的博客">
<meta property="og:description" content="前言安装 1npm install --save egg-sequelize mysql2  配置 12345678910111213141516&#x2F;&#x2F; config&#x2F;plugin.tssequelize: &amp;#123;  enable: true,  package: &amp;#x27;egg-sequelize&amp;#x27;,&amp;#125;,    &#x2F;&#x2F; config&#x2F;config.defaullt.ts">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2020-08-25T15:57:52.000Z">
<meta property="article:modified_time" content="2020-08-25T16:01:45.022Z">
<meta property="article:author" content="幽辰">
<meta property="article:tag" content="egg">
<meta property="article:tag" content="Typescript">
<meta property="article:tag" content="数据库">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://youchen12138.gitee.io/hexo/2020/08/25/egg-ts%E4%BD%BF%E7%94%A8sequelize/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'en'
  };
</script>

  <title>egg+ts使用sequelize | 幽辰的博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/hexo/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">幽辰的博客</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/hexo/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/hexo/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>Tags<span class="badge">23</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/hexo/categories/" rel="section"><i class="fa fa-th fa-fw"></i>Categories<span class="badge">14</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/hexo/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>Archives<span class="badge">127</span></a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="en">
    <link itemprop="mainEntityOfPage" href="https://youchen12138.gitee.io/hexo/2020/08/25/egg-ts%E4%BD%BF%E7%94%A8sequelize/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/hexo/images/avatar.jpg">
      <meta itemprop="name" content="幽辰">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="幽辰的博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          egg+ts使用sequelize
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>

              <time title="Created: 2020-08-25 23:57:52" itemprop="dateCreated datePublished" datetime="2020-08-25T23:57:52+08:00">2020-08-25</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">Edited on</span>
                <time title="Modified: 2020-08-26 00:01:45" itemprop="dateModified" datetime="2020-08-26T00:01:45+08:00">2020-08-26</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">In</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/hexo/categories/egg/" itemprop="url" rel="index"><span itemprop="name">egg</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p><strong>安装</strong></p>
<figure class="highlight powershell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install -<span class="literal">-save</span> egg<span class="literal">-sequelize</span> mysql2</span><br></pre></td></tr></table></figure>

<p><strong>配置</strong></p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// config/plugin.ts</span></span><br><span class="line">sequelize: &#123;</span><br><span class="line">  enable: <span class="literal">true</span>,</span><br><span class="line">  package: <span class="string">&#x27;egg-sequelize&#x27;</span>,</span><br><span class="line">&#125;,</span><br><span class="line">    </span><br><span class="line"><span class="comment">// config/config.defaullt.ts</span></span><br><span class="line">config.sequelize = &#123;</span><br><span class="line">  dialect: <span class="string">&#x27;mysql&#x27;</span>, <span class="comment">// 表示是mysql数据库</span></span><br><span class="line">  host: <span class="string">&#x27;127.0.0.1&#x27;</span>,</span><br><span class="line">  port: <span class="number">3306</span>,</span><br><span class="line">  database: <span class="string">&#x27;test&#x27;</span>,</span><br><span class="line">  username: <span class="string">&#x27;root&#x27;</span>,</span><br><span class="line">  password: <span class="string">&#x27;123456&#x27;</span>,</span><br><span class="line">  timezone: <span class="string">&#x27;+08:00&#x27;</span>, <span class="comment">// 表示为东八区的时间</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p><strong>model 创建</strong></p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// app/model/User.ts</span></span><br><span class="line"><span class="keyword">import</span> &#123; Application &#125; <span class="keyword">from</span> <span class="string">&#x27;egg&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span>(<span class="params">app: Application</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> &#123; STRING, INTEGER, BIGINT &#125; = app.Sequelize;</span><br><span class="line">  <span class="keyword">const</span> User = app.model.define(<span class="string">&#x27;users&#x27;</span>, &#123;</span><br><span class="line">    id: &#123;</span><br><span class="line">      <span class="keyword">type</span>: INTEGER, <span class="comment">// INTEGER就是mysql中的int</span></span><br><span class="line">      primaryKey: <span class="literal">true</span>,</span><br><span class="line">      autoIncrement: <span class="literal">true</span>, <span class="comment">// 自动增长</span></span><br><span class="line">    &#125;,</span><br><span class="line">    app_name: STRING(<span class="number">20</span>),</span><br><span class="line">    j: BIGINT,</span><br><span class="line">    url: STRING(<span class="number">100</span>),</span><br><span class="line">    country: STRING(<span class="number">10</span>),</span><br><span class="line">  &#125;, &#123;</span><br><span class="line">    <span class="comment">// timestamps: false, // 去除createAt updateAt</span></span><br><span class="line">    createdAt: <span class="literal">false</span>, <span class="comment">// 表示不启用created_at</span></span><br><span class="line">    updatedAt: <span class="literal">false</span>, <span class="comment">// 表示不启用updated_at</span></span><br><span class="line">    freezeTableName: <span class="literal">true</span>, <span class="comment">// 使用自定义表名</span></span><br><span class="line">    <span class="comment">// 使用自定义表名之后上面写的users就直接就是你的表名，如果不加的话，你就可以写user，但是自己的表名为users，程序会自动将s加上</span></span><br><span class="line">    tableName: <span class="string">&#x27;users&#x27;</span>, <span class="comment">// 自定义的表名，也可以不写，直接用define后面的也可以</span></span><br><span class="line">    <span class="comment">// 只要你使用了freezeTableName，程序就不会自动给你加上s了</span></span><br><span class="line">  &#125;);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">class</span> <span class="keyword">extends</span> User &#123;&#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="命令"><a href="#命令" class="headerlink" title="命令"></a>命令</h2><h3 id="增加数据"><a href="#增加数据" class="headerlink" title="增加数据"></a>增加数据</h3><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> res = <span class="keyword">await</span> ctx.model.User.create(&#123;</span><br><span class="line">    app_name: <span class="string">&#x27;xxx&#x27;</span>,</span><br><span class="line">    j: <span class="number">10</span>,</span><br><span class="line">    url: <span class="string">&#x27;http://xxx.com&#x27;</span>,</span><br><span class="line">    country: <span class="string">&#x27;CN&#x27;</span>,</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h3 id="查找"><a href="#查找" class="headerlink" title="查找"></a>查找</h3><p><strong>查找表中全部数据</strong></p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> res = <span class="keyword">await</span> ctx.model.User.findAll();</span><br></pre></td></tr></table></figure>

<p><strong>投影表中部分字段</strong></p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> res = <span class="keyword">await</span> ctx.model.User.findAll(&#123;</span><br><span class="line">    attributes: [ <span class="string">&#x27;id&#x27;</span>, <span class="string">&#x27;app_name&#x27;</span> ], <span class="comment">// 投影id和app_name</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p><strong>条件查询</strong></p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> res = <span class="keyword">await</span> ctx.model.User.findAll(&#123;</span><br><span class="line">    attributes: [ <span class="string">&#x27;id&#x27;</span>, <span class="string">&#x27;app_name&#x27;</span> ],</span><br><span class="line">    where: &#123;</span><br><span class="line">      id: <span class="number">2</span>,</span><br><span class="line">    &#125;,</span><br><span class="line">    limit: <span class="number">1</span>, <span class="comment">// 限制</span></span><br><span class="line">    offset: <span class="number">1</span>, <span class="comment">// 偏移</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p><strong>根据主键查找</strong></p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> res = <span class="keyword">await</span> ctx.model.User.findByPk(<span class="number">1</span>);</span><br></pre></td></tr></table></figure>

<h3 id="修改数据"><a href="#修改数据" class="headerlink" title="修改数据"></a>修改数据</h3><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> res = <span class="keyword">await</span> ctx.model.User.findByPk(<span class="number">22</span>);</span><br><span class="line">res?.update(&#123; app_name: <span class="string">&#x27;xxx&#x27;</span> &#125;);</span><br></pre></td></tr></table></figure>

<p>查找到相应元组再更新数据</p>
<h3 id="删除数据"><a href="#删除数据" class="headerlink" title="删除数据"></a>删除数据</h3><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> res = <span class="keyword">await</span> ctx.model.User.findByPk(<span class="number">22</span>);</span><br><span class="line">res?.destroy();</span><br></pre></td></tr></table></figure>
    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/hexo/tags/egg/" rel="tag"># egg</a>
              <a href="/hexo/tags/Typescript/" rel="tag"># Typescript</a>
              <a href="/hexo/tags/%E6%95%B0%E6%8D%AE%E5%BA%93/" rel="tag"># 数据库</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/hexo/2019/05/25/%E8%B7%A8%E5%9F%9F/" rel="prev" title="跨域">
      <i class="fa fa-chevron-left"></i> 跨域
    </a></div>
      <div class="post-nav-item">
    <a href="/hexo/2020/08/26/bootstrap%E7%BB%84%E4%BB%B6/" rel="next" title="bootstrap组件">
      bootstrap组件 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%89%8D%E8%A8%80"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%91%BD%E4%BB%A4"><span class="nav-number">2.</span> <span class="nav-text">命令</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%A2%9E%E5%8A%A0%E6%95%B0%E6%8D%AE"><span class="nav-number">2.1.</span> <span class="nav-text">增加数据</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%9F%A5%E6%89%BE"><span class="nav-number">2.2.</span> <span class="nav-text">查找</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BF%AE%E6%94%B9%E6%95%B0%E6%8D%AE"><span class="nav-number">2.3.</span> <span class="nav-text">修改数据</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%88%A0%E9%99%A4%E6%95%B0%E6%8D%AE"><span class="nav-number">2.4.</span> <span class="nav-text">删除数据</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="幽辰"
      src="/hexo/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">幽辰</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/hexo/archives/">
        
          <span class="site-state-item-count">127</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/hexo/categories/">
          
        <span class="site-state-item-count">14</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/hexo/tags/">
          
        <span class="site-state-item-count">23</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">幽辰</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a>
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/hexo/lib/anime.min.js"></script>
  <script src="/hexo/lib/velocity/velocity.min.js"></script>
  <script src="/hexo/lib/velocity/velocity.ui.min.js"></script>

<script src="/hexo/js/utils.js"></script>

<script src="/hexo/js/motion.js"></script>


<script src="/hexo/js/schemes/pisces.js"></script>


<script src="/hexo/js/next-boot.js"></script>




  















  

  

</body>
</html>
